package com.xxx.service;

import com.xxx.dao.AccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * @version v1.0
 * @Description:
 * @Author zhanzhongxin
 * @Date 2021/8/18 14:22
 * @Copyright 博为峰
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private DataSourceTransactionManager transactionManager;

//    @Override
//    public void transfer(String from, String to, int money) {
//        //zhangsan转账给lis   zhangsan的-money  lisi的+money
//        accountDao.updateAccount(from, -money);
//        System.out.println(1 / 0);
//        accountDao.updateAccount(to, money);
//    }

    @Override
    public void transfer(String from, String to, int money) {
        //1.事务管理器
//        final DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        //2.事务定义
        final DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        //事务隔离级别
        definition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        //事务传播行为
        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        //超时时间 -1永不超时
        definition.setTimeout(-1);
        //是否只读
        definition.setReadOnly(false);
        //3.事务状态
        final TransactionStatus status = transactionManager.getTransaction(definition);
        try {
            accountDao.updateAccount(from, -money);
            System.out.println(1 / 0);
            accountDao.updateAccount(to, money);
            transactionManager.commit(status);//提交
        } catch (Exception e) {
            transactionManager.rollback(status);//回滚
            e.printStackTrace();
        }
    }
}
